package com.gitee.liuzhi.common.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang3.StringUtils;

/**
 * @Author liuzhi
 * @Date 2023/8/29 22:10
 * @Version 1.0
 * @Description 拼音工具类
 */
public class PinYinUtil {


    /**
     * 汉语转拼音，兼容多音字，假声字
     *
     * @param str
     * @param containTone 是否带声调
     * @return
     */
    public static String toPinYin(String str, boolean containTone) {
        if (StringUtils.isBlank(str)) {
            return StringUtils.EMPTY;
        }
        HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
        if (containTone) {
            outputFormat.setToneType(HanyuPinyinToneType.WITH_TONE_MARK);
        } else {
            outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        }

        outputFormat.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
        try {
            return PinyinHelper.toHanYuPinyinString(str, outputFormat, "", true);
        } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
            badHanyuPinyinOutputFormatCombination.printStackTrace();
        }
        return null;
    }

    /**
     * 如果关键词拼音码，返回大写，否则返回空
     */
    public static String getNameCodeByKeywords(String keyword) {
        if (StringUtils.isEmpty(keyword)) {
            return null;
        }
        keyword = keyword.toUpperCase();
        if (keyword.matches("[A-Z][0-9A-Z]*")) {
            return keyword;
        }
        return null;
    }

}
